var element,form,table,treeTable,tableInstance;
var test = [
    {code:'123',name:'lisi',classify:'xx',status:1,type:1,sort:2,checked:false},
    {code:'123',name:'lisi',classify:'xx',status:1,type:1,sort:2,checked:true}
]
// 表格初始化数据
var tableInitData = {
    orderGoodsTable:JSON.parse(JSON.stringify(test)),
    orderClassifyTable:JSON.parse(JSON.stringify(test)),
    shoppingGoodsTable:JSON.parse(JSON.stringify(test)),
    shoppingClassifyTable:JSON.parse(JSON.stringify(test)),
    couponTable:JSON.parse(JSON.stringify(test)),
    activityTable:JSON.parse(JSON.stringify(test)),
    couponPackageTable:JSON.parse(JSON.stringify(test)),
}
// 点餐选项卡下 树表格初始化数据
var TreeTableInitData = [
    {
      "id": 1,
      "name": "aa",
      "sex": "male",
      "pid": -1,
      "open": true,
      "updateTime": "2018/07/21 13:56:43",
      "state": 0
    },
    {
      "id": 2,
      "name": "bb",
      "sex": "male",
      "pid": 1,
      "open": true,
      "updateTime": "2018/07/21 13:56:43",
      "state": 0
    },
    {
      "id": 31,
      "name": "cc",
      "sex": "male",
      "pid": 1,
      "open": true,
      "updateTime": "2018/07/21 13:56:43",
      "state": 0
    },
    {
        "id": 4,
        "name": "dd",
        "sex": "male",
        "pid": -1,
        "open": true,
        "updateTime": "2018/07/21 13:56:43",
        "state": 0
      },
      {
        "id": 5,
        "name": "ee",
        "sex": "male",
        "pid": 4,
        "open": true,
        "updateTime": "2018/07/21 13:56:43",
        "state": 0
      }];
layui.config({
    base: './'
})
layui.use(['element', 'form', 'table','treeTable'],function(){
    element = layui.element;
    form = layui.form;
    table = layui.table;
    treeTable = layui.treeTable;
    // 初始化
    init();
    // 监听radio事件
    form.on('radio(unify-radio)',function(data){
        var type = $(data.elem).data('type');
        var value = $(data.elem).data('value');
        switch(type){
            case 'order-choose-page':
                var orderObj = {
                    1:'.order-control-1',
                    2:'.order-control-2',
                    3:'',
                    4:''
                }
                addLinkTools.controlShow(value,orderObj);
                if(value == 2){
                    orderClassifyTable(tableInitData.orderClassifyTable);
                }
            break;
            case 'shopping-choose-page':
                var shoppingObj = {
                    1:'.shopping-control-show-1',
                    2:'.shopping-control-show-2',
                    3:'.shopping-control-show-3'
                }
                addLinkTools.controlShow(value,shoppingObj);
                if(value == 2){
                    shoppingClassifyTable(tableInitData.shoppingClassifyTable);
                }
            break;
            case 'coupon':
                var couponObj = {
                    1:'',
                    2:'',
                    3:'.coupon-control-3',
                    4:'.coupon-control-4',
                }
                addLinkTools.controlShow(value,couponObj);
                if(value == 3){
                    couponTable(tableInitData.couponTable);
                }else if(value == 4){
                    couponPackageTable(tableInitData.couponPackageTable);
                }
            break;
            case 'orderAppointShop':
                var orderAppoint = {
                    1:'',
                    2:'.order-appoint-shop-2'
                }
                addLinkTools.controlShow(value,orderAppoint);
        }
    })
    // 监听tab切换事件,加载相应的表格
    element.on('tab(addLinkTab)',function(data){
        switch(data.index){
            case 1:
                shoppingGoodsTable(tableInitData.shoppingGoodsTable);
            break;
            case 3:
                activityTable(tableInitData.activityTable);
            break;
        }
    })
    // 监听表格中的按钮,取消选择和选择之间替换,并且改变数据中相对应的项的checked的值
    $(document).on('click','.table-input-unify',function(){
        var type = $(this).data('type');
        var origin = $(this).data('origin');
        var index = $(this).data('index');
        if(type == 'cancel'){
            // 取消选中
            tableInitData[origin][index].checked = false;
            $(this).hide().next().show();
        }else{
            tableInitData[origin][index].checked = true;
            $(this).hide().prev().show();
        }
    })
    // 树表格的搜索 和 清除搜索 按钮事件
    // 搜索
    $('#btnSearch').click(function () {
        var keywords = $('#edtSearch').val();
        if (keywords) {
            tableInstance.filterData(keywords);
        } else {
            tableInstance.clearFilter();
        }
    });

    // 清除搜索
    $('#btnClearSearch').click(function () {
        tableInstance.clearFilter();
        $('#edtSearch').val('')
    });
})
// 初始化
function init(){
    orderGoodsTable(tableInitData.orderGoodsTable);
    partShopTreeTable();
}
// 点餐/商品 表格
function orderGoodsTable(data){
    var cols = [[
        {field:'code',title:'商品编码',align:'center'},
        {field:'name',title:'名称',align:'center'},
        {field:'classify',title:'所属类别',align:'center'},
        {field:'status',title:'状态',align:'center'},
        {field:'',title:'操作',align:'center',templet:addLinkTools.productOperator('orderGoodsTable')}
    ]]
    table.render({
        elem:'#orderGoodsTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 点餐/分类 表格
function orderClassifyTable(data){
    var cols = [[
        {field:'classify',align:'center',title:'分类名称'},
        {field:'type',align:'center',title:'类型'},
        {field:'sort',align:'center',title:'排序'},
        {field:'',align:'center',title:'操作',templet:addLinkTools.productOperator('orderClassifyTable')}
    ]];
    table.render({
        elem:'#orderClassifyTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 树形表格渲染
function partShopTreeTable(data){
    // 该插件 文档 https://gitee.com/whvse/treetable-lay/wikis/pages
    tableInstance = treeTable.render({
        elem: '#partShopTreeTable',
        data:TreeTableInitData,
        cols:[[
            {type:'checkbox'},
            {field:'name',title:'门店列表'}
        ]],
        tree:{
            iconIndex: 1,
                isPidData: true,
                idName: 'id',
                pidName: 'pid'
        }
    })
    treeTable.on('checkbox(partShopTreeTable)',function(data){
        var selectData;
        // 如果是全选 或 全不选
        if(data.type == 'all' && data.checked == false){
            selectData = [];
        }else if(data.type == 'all' && data.checked == true){
            selectData = TreeTableInitData
        }else{
            selectData = tableInstance.checkStatus();
        }
        userSelectTreeTable(selectData);
    })
}
// 用户已经选择的数据渲染成树表格
function userSelectTreeTable(data){
    treeTable.render({
        elem: '#userSelectTreeTable',
        data:data,
        cols:[[
            // {type:'checkbox'},
            {field:'name',title:'已选择门店列表'},
            {field:'',title:'操作',align:'center',templet:function(){
                return `<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>`
            }}
        ]],
        tree:{
            iconIndex: 0,
                isPidData: true,
                idName: 'id',
                pidName: 'pid'
        }
    })
    treeTable.on('tool(userSelectTreeTable)', function (obj) {
        var event = obj.event;
        if (event === 'del') {
            layer.msg('删除成功');
            console.log(obj)
            tableInstance.setCheckedUser([obj.data.id]);
            obj.del();
        }
    });
}
// 商城/商品
function shoppingGoodsTable(data){
    var cols = [[
        {field:'name',align:'center',title:'名称'},
        {field:'classfigy',align:'center',title:'所属分类'},
        {field:'status',align:'center',title:'状态'},
        {field:'stocks',align:'center',title:'库存'},
        {field:'',align:'center',title:'操作',templet:addLinkTools.productOperator('shoppingGoodsTable')}
    ]]
    table.render({
        elem:'#shoppingGoodsTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 商城/分类
function shoppingClassifyTable(data){
    var cols = [[
        {field:'classify',align:'center',title:'分类名称'},
        {field:'sort',align:'center',title:'排序'},
        {field:'',align:'center',title:'操作'}
    ]]
    table.render({
        elem:'#shoppingClassifyTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 优惠券
function couponTable(data){
    var cols = [[
        {field:'name',align:'center',title:'优惠券名称'},
        {field:'discound',align:'center',title:'折扣'},
        {field:'condition',align:'center',title:'条件'},
        {field:'time',align:'center',title:'有效期'},
        {field:'',align:'center',title:'操作',templet:addLinkTools.productOperator('couponTable')}
    ]]
    table.render({
        elem:'#couponTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 优惠券包
function couponPackageTable(data){
    var cols = [[
        {field:'name',align:'center',title:'券名称'},
        {field:'range',align:'center',title:'适用范围'},
        {field:'stock',align:'center',title:'库存'},
        {field:'time',align:'center',title:'有效期'},
        {field:'terrace',align:'center',title:'发券平台'},
        {field:'',align:'center',title:'操作',templet:addLinkTools.productOperator('couponPackageTable')}
    ]]
    table.render({
        elem:'#couponPackageTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}
// 营销活动
function activityTable(data){
    var cols = [[
        {field:'name',title:'活动名称',align:'center'},
        {field:'type',title:'活动类型',align:'center'},
        {field:'time',title:'有效期',align:'center'},
        {field:'',title:'操作',align:'center',templet:addLinkTools.productOperator('activityTable')}
    ]]
    table.render({
        elem:'#activityTable',
        data:data,
        cols:cols,
        limit:data.length
    })
}

// 公共方法集合
var addLinkTools = {
    // 根据配置控制不同状态下 相应的dom是否显示
    controlShow:function(key,obj){
        $.each(obj,function(k,o){
            if(k == key){
                if(o){
                    $(o).show();
                }
            }else{
                if(o){
                    $(o).hide();
                }
            }
        })
    },
    productOperator:function(origin){
        return function(d){
           return `
            <button  style="display:${d.checked ? 'inline-block' : 'none'}" data-type="cancel" data-index="${d.LAY_TABLE_INDEX}" data-origin="${origin}" class="table-input-unify layui-btn layui-btn-sm layui-btn-primary">取消选择</button>
            <button  style="display:${d.checked ? 'none' : 'inline-block'}" data-type="sure" data-index="${d.LAY_TABLE_INDEX}" data-origin="${origin}" class="table-input-unify layui-btn layui-btn-sm layui-btn-normal">选择</button>
            ` 
        }
    }
}
